package com.rookie.damaihelper

import android.accessibilityservice.AccessibilityService
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.app.NotificationCompat
import org.slf4j.Logger
import org.slf4j.LoggerFactory

/*
 *  @项目名：  AddFriend 
 *  @包名：    com.rookie.addfriend
 *  @文件名:   AddFriendService
 *  @创建者:   rookietree
 *  @创建时间:  2023/3/17 15:34
 *  @描述：
 */
class DaMaiHelperService : AccessibilityService(), UserManager.IStartListener {

    var log: Logger = LoggerFactory.getLogger(DaMaiHelperService::class.java)

    companion object {
        //首页-我的
        const val ME_UI = "com.tencent.mm.ui.LauncherUI"  // 我的

        //演唱会信息页
        const val LIVE_DETAIL_UI =
            "com.tencent.mm.plugin.subapp.ui.friend.FMessageConversationUI"

        //购票选择页
        const val LIVE_SELECT_DETAIL_UI =
            "com.tencent.mm.ui.vas.VASCommonActivity"

        //输入手机号
        const val LIVE_TOTAL_UI = "com.tencent.mm.ui.vas.VASCommonActivity1"

        const val ID_LIVE_DETAIL_BUY = "tv_left_main_text"//详情页-开抢
        const val ID_CONFIRM_BUY = "btn_buy" //确认购买

        const val STEP_READY = 0
        const val STEP_FIRST = 1
        const val STEP_SECOND = 2
        const val STEP_THIRD = 3
        const val STEP_FOURTH = 4
        const val STEP_FINISH = 5
    }

    private var isStop = false
    private var step = STEP_READY

    private var overlayView: View? = null
    private var mWindowManager: WindowManager? = null
    private val kaiQiangStr = "即将开抢"
    private val queHuoStr = "缺货登记"

    override fun onCreate() {
        super.onCreate()
        // 创建Notification渠道，并开启前台服务
        createForegroundNotification()?.let { startForeground(1, it) }
        UserManager.startListener = this
    }

    private fun showWindow() {
        if (mWindowManager == null) {
            // 获取 WindowManager
            mWindowManager = getSystemService(WINDOW_SERVICE) as WindowManager
            // 创建一个悬浮窗口 View
            overlayView =
                (getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater).inflate(
                    R.layout.float_app_view, null
                ) as ConstraintLayout
            // 设置悬浮窗口参数
            val flag =
                (WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN)
            val params = WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                flag,
                PixelFormat.TRANSLUCENT
            )
            val tvSwitch = overlayView?.findViewById<TextView>(R.id.tv_switch)
            tvSwitch?.setOnClickListener {
                stopForeground(true)
                mWindowManager?.removeView(overlayView)
                stopSelf()
                isStop = true
            }
            // 设置窗口布局的位置和大小
            params.gravity = Gravity.END or Gravity.TOP
            // 将悬浮窗口 View 添加到 WindowManager 中
//            mWindowManager?.addView(overlayView, params)
        }
    }

    private var hasCheck: Boolean = false

    override fun onServiceConnected() {
        log.info("无障碍服务连接上了")
        super.onServiceConnected()
    }


    fun getNodeById(id: String): AccessibilityNodeInfo? {
        rootInActiveWindow?.findAccessibilityNodeInfosByViewId(
            id
        ).let {
            if (!it.isNullOrEmpty()) {
                return it[0]
            }
        }
        return null
    }


    /**
     * 监听窗口变化的回调
     */
    override fun onAccessibilityEvent(event: AccessibilityEvent?) {


        logD("event_name:$event")
        if (event == null) {
            log.warn("event_name => $event")
            return
        }
        val currentActivity = event?.className.toString()
        fullPrintNode("当前", event?.source)
        if (event?.source?.text?.contains("来源") == true) {
            log.info("当前在检索后的信息界面，下一步‘添加到通讯录’")
            step = STEP_FOURTH
        }

//        log.info("当前 $event")


        if (event?.eventType == AccessibilityEvent.TYPE_VIEW_FOCUSED) {

            fullPrintNode("聚焦了", event.source)

        } else if (event?.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {

            val currentActivity = event.className.toString()
            when (currentActivity) {

                ME_UI -> {
                    step = STEP_FIRST
                    firstStep(event)
                }

                LIVE_DETAIL_UI -> {
                    step = STEP_SECOND
                    secondStep(event)
//                    startQ(event)
                }

                LIVE_SELECT_DETAIL_UI -> {
                    // 搜索手机号的页面
                    step = STEP_THIRD
                    thirdStep(event)

//                    event.source?.let { source ->
//                        val buyView2 = source.getNodeByText("帐号/手机号")
//                        buyView2?.click()
//                        sleep(500)
//
//                    }
//                    confirmOrder(event)
                }

                LIVE_TOTAL_UI -> {
//                    event.source?.let { source ->
//                        val buyView2 = source.getNodeByText("帐号/手机号")
//
//                        buyView2.setText("18010472947")
//
//                    }
//                    step = STEP_FOURTH
//                    requestOrder(event)
                }
            }
        } else if (event?.eventType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
//            fullPrintNode("content_change", event.source)
            log.info("content_change $event")
//            if (event?.source?.text?.contains("搜索") == true) {
//
//
//                if ("android.widget.FrameLayout" == currentActivity) {
//
//                    fourStep(event)
//                }
//
//            }
//
//

            // 确定当前的界面


            when (step) {
                STEP_SECOND -> {
//                    startQ(event)
                }

                STEP_THIRD -> {
//                    confirmOrder(event)
                    step = STEP_FOURTH
                    fourStep(event)
                }

                STEP_FOURTH -> {
                    step = STEP_FINISH
                    fiveStep(event)
                }

                STEP_FINISH -> {

                }
            }
        } else {
            log.warn("没有处理 $event")
        }
    }


    private fun firstStep(event: AccessibilityEvent) {
        log.info("第一步：找到通讯录，新的朋友 $event")
        event.source?.let { source ->
            sleep(500)
            val wantView = source.getNodeByText("通讯录")
            wantView?.click()
            sleep(500)
            val buyView = source.getNodeByText("新的朋友")
            buyView?.click()
            sleep(500)
        }
    }

    private fun secondStep(event: AccessibilityEvent) {
        log.info("第二步：找到添加朋友，帐号/手机号 $event")

        event.source?.let { source ->
            val buyView1 = source.getNodeByText("添加朋友")
            buyView1?.click()
            sleep(500)
            val buyView2 = source.getNodeByText("帐号/手机号")
            buyView2?.click()
        }
    }


    private fun thirdStep(event: AccessibilityEvent) {
        log.info("第三步：复制粘贴手机号$event")
        val s = "com.tencent.mm:id/cd7"
        getNodeById(s).let { n ->


            var clear = getNodeById("com.tencent.mm:id/bde")

            clear?.click()

            val clipboard =
                this.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            //使用剪切板
            var clip = ClipData.newPlainText("text", "18522607205");
            clipboard.setPrimaryClip(clip);
            //焦点（n是AccessibilityNodeInfo对象）
            n?.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
            n?.performAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
            //粘贴进入内容
            n?.performAction(AccessibilityNodeInfo.ACTION_PASTE);
            sleep(1000)
        }
    }

    private fun fourStep(event: AccessibilityEvent) {
        log.info("第四步：点击搜索+手机号，查找是否存在 $event")
        getNodeById("com.tencent.mm:id/kms").let { n1 ->
            logD("event_name:$n1")
//                n1?.click()
            if (n1 != null) {

                val parent = n1?.parent

                parent?.let { n ->
                    if (n != null) {

                        n?.click()
                        sleep(500)
                        log.info("点击搜索手机号了，等待好友信息出现，再点击添加到通讯录")
//                            var addContact = getNodeById("com.tencent.mm:id/iwg")
//                            addContact.let { n ->
//                                fullPrintNode("点击添加了1", event.source)
//
//                                if (n?.isClickable == true) {
//                                    n?.click()
//                                    sleep(1000)
//                                }
//                            }

                    }
                }

            }
        }
    }

    private fun fiveStep(event: AccessibilityEvent) {

        log.info("第五步:点击‘添加到通讯录’ $event")

        var addContact = getNodeById("com.tencent.mm:id/iwg")
        addContact.let { n ->

            if (n != null && n?.isClickable == true) {
//                if (event?.source != null && event.source.text!=null && event.source.text.contains("搜索")){
                    fullPrintNode("点击添加‘添加到通讯录’了", event.source)
                    n?.click()
                    sleep(500)
//                }
            }
        }

        var addContact1 = getNodeById("com.tencent.mm:id/khj")

        addContact1?.parent?.let { n ->
            if (n != null) {
                if (n.isClickable){
                    log.info("点击添加‘添加到通讯录’了")
                    n.click()
                }
            }

        }


    }


    private fun startQ(event: AccessibilityEvent) {
        println("开始")
        event.source?.let { source ->
            val startBuy = source.getNodeById(dmNodeId(ID_LIVE_DETAIL_BUY))
            startBuy?.text()?.let {
                if (it != kaiQiangStr && it != queHuoStr) {
                    startBuy.click()
                    logD("buy_text:$it")
                }
            }
        }
    }

    private fun confirmOrder(event: AccessibilityEvent) {
        event.source?.let { source ->
            sleep(100)
            val buyView = source.getNodeById(dmNodeId(ID_CONFIRM_BUY))
            buyView?.click()
        }
    }

    private fun requestOrder(event: AccessibilityEvent) {
        event.source?.let { source ->
            val nodeByText = source.getNodeByText("提交订单", true)
            nodeByText?.let {
                it.click()
                step = STEP_FINISH
            }
        }
    }

    override fun onStart() {
        isStop = false
        hasCheck = false
        step = STEP_READY
        showWindow()
    }

    override fun onInterrupt() {

    }

    private fun createForegroundNotification(): Notification? {
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
        val channelId = "damai"
        notificationManager?.createNotificationChannel(
            NotificationChannel(
                channelId, "大麦抢票", NotificationManager.IMPORTANCE_HIGH // 发送通知的等级，此处为高
            )
        )
        return NotificationCompat.Builder(this, channelId)
            // 设置点击notification跳转，比如跳转到设置页
            .setContentIntent(
                PendingIntent.getActivity(
                    this, 0, Intent(this, MainActivity::class.java), FLAG_IMMUTABLE
                )
            ).setSmallIcon(R.drawable.ic_app) // 设置小图标
            .setContentTitle(getString(R.string.acc_des)).setContentText("大麦抢票")
            .setTicker("大麦抢票").build()
    }

    override fun onDestroy() {
        stopForeground(true)
        mWindowManager?.removeView(overlayView)
        super.onDestroy()
    }

}